package com.xhixm.chatbot.application.job;

import com.alibaba.fastjson.JSON;
import com.xhixm.chatbot.domain.ai.IOpenAI;
import com.xhixm.chatbot.domain.zsxq.IZsxqApi;
import com.xhixm.chatbot.domain.zsxq.model.aggregates.UnAnsweredQuestionsAggregates;
import com.xhixm.chatbot.domain.zsxq.model.vo.Topics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;


@EnableScheduling
@Configuration
public class ChatbotSchedule {

    private Logger logger = LoggerFactory.getLogger(ChatbotSchedule.class);

    @Value("${my-chatbot.cookie}")
    private String cookie;
    @Value("${my-chatbot.groupId}")
    private String groupId;

    @Resource
    private IZsxqApi zsxqApi;

    @Resource
    private IOpenAI openAI;


    // 每五秒查询一次   0/5 * * * * ?
    @Scheduled(cron = "0/30 * * * * ?")
    public void run() {
        try {
            if (new Random().nextBoolean()) {
                logger.info("随机打烊中。。。");
                return;
            }

            GregorianCalendar calendar = new GregorianCalendar();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour > 23 || hour <7) {
                logger.info("睡觉了嗷。。。");
                return;
            }

            // 查出问题
            UnAnsweredQuestionsAggregates unAnsweredQuestionsAggregates = zsxqApi.queryUnAnsweredQuestionsTopicId(groupId, cookie);


            logger.info("检索结果:{}" , JSON.toJSONString(unAnsweredQuestionsAggregates));
            List<Topics> topics = unAnsweredQuestionsAggregates.getResp_data().getTopics();
            if (null == topics || topics.isEmpty()){
                logger.info("本次检索未查询到");
                return;
            }

            // Ai回答
            Topics topic = topics.get(0);
            String answer = openAI.doChatGPT(topic.getQuestion().getText().trim(),topic.getQuestion().getOwner().getUser_id());

            // 回复
            boolean status = zsxqApi.answer(groupId, cookie, topic.getTopic_id(), answer, false);
            logger.info("编号:{} 问题:{} 回答:{} 状态:{}",topic.getTopic_id(),topic.getQuestion(),answer,status);

        } catch (Exception e) {
            logger.error("自动回答问题异常",e);
        }
    }

}
